#ifndef _GAMETIMER_H_
#define _GAMETIMER_H_

#include <vector>
#include "SDL.h"

#include "compat.h"
#include "../foreach.h"

// Implements game timer with frame skipping and system event handling

// Usage:

// GameTimer timer(60, -1, false); // run at 60 fps, infinite max fskip, no event handling
// while(game_not_ended) {
//     timer.wait();
//     while(timer.logic()) {
//         // logic if any
//     }
//     // draw
// }

// Note that you must have both
//     time.wait();
// and
//     while(timer.logic()) {}
// even if you don't do any logic yourself.


namespace util {

class GameTimer {
public:
	// Create a GameTimer;
	//     fps - targeted fps
	//     maxfskip - how many frames to skip at most;
	//         -1  for infinite; immediate correction
	//          0  for no frame skipping
	//          1+ for smooth transition; define speed of correction
	//     enable_events - enable user events or not
	//          true   lets you do while(SDL_PollEvent(...))
	//          false  clears events automatically so they won't stack
	GameTimer(int fps, int maxfskip, bool events);

	// Reset frameskip timer.
	// Call when returning from a function or a break.
	void resume();

	// Wait until it's time to do logic
	void wait();

	// Returns true while it's time to do logic.
	// Call in a while loop:
	//     while(timer.logic()) {
	//         // logic
	//     }
	// Takes care of system events like window closing and window
	// resizing.
	bool logic();

private:
	// Handles system events but nothing else
	void events();

	bool enable_events;
	int fskip;
	int maxfskip;
	uint32 nextround;
	uint32 roundtime;

	static bool sdl_quit;
};

}

#endif
